package api.ws.server.msg.impl;

import api.ws.server.msg.IMessageExecutor;
import basic.common.Cst;
import basic.common.ws.Message;
import basic.common.ws.WsContext;
import basic.webflux.cache.RedisKey;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @创建人 xiaojiancheng
 * @时间 2021/1/5
 * @描述  回声测试 同心跳
 */
@Component
public class EchoMessageExecutor implements IMessageExecutor {
    @Resource
    RedisKey redisKey;

    @Override
    public Mono<Message> execute(WsContext context) {
        Message rtn = new Message();
        Message msg = context.getMessage();

        rtn.setFromId(msg.getFromId());
        rtn.setToId(msg.getFromId());
        rtn.setType(msg.getType());
        rtn.setText("echo");
        rtn.setStatus(Cst.Status.N);

        //  这里直接回复 就不走消息队列了
        return Mono.create(item -> {
            Channel channel = context.getChannel();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(rtn)));

            item.success();
        });
    }

    @Override
    public String type() {
        return Cst.MessageType.ECHO;
    }
}
